package com.example.combat.service;

import com.example.combat.pojo.UserInfo;
import com.example.combat.repository.UserRepository;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Objects;

/**
 * @author 石一歌
 * @since 2024-01-06 16:29
 */
@Service
public class UserService {
    @Resource
    private UserRepository userRepository;

    public String login(String username, String password) {
        UserInfo userInfo = userRepository.findByUsernameAndPassword(username, password);
        if (Objects.isNull(userInfo)) {
            return "ERROR";
        }
        return "SUCCESS";
    }

    public String register(UserInfo userInfo) {
        if (checkUserExists(userInfo.getUsername())) {
            throw new RuntimeException("User already registered");
        }
        userInfo.setCreateTime(new Date());
        System.out.println(userInfo);
        userRepository.save(userInfo);
        return "register success";
    }

    private boolean checkUserExists(String username) {
        return Objects.nonNull(userRepository.findByUsername(username));
    }

}
